package net.dgg.dggcloud.service.iboss.service.sc;

import net.dgg.dggcloud.service.common.base.SessionManager;
import net.dgg.dggcloud.service.common.base.service.BaseService;
import net.dgg.dggcloud.service.entity.org.OrganizationEntity;
import net.dgg.dggcloud.service.entity.user.User;
import net.dgg.dggcloud.service.iboss.constant.BusCodeConstant;
import net.dgg.dggcloud.service.iboss.constant.ScOperationConstant;
import net.dgg.dggcloud.service.iboss.constant.ScStatusConstant;
import net.dgg.dggcloud.service.iboss.dao.sc.WaitAllocationDao;
import net.dgg.dggcloud.service.iboss.entity.ScProFlowOperating;
import net.dgg.dggcloud.service.iboss.entity.ScProOrder;
import net.dgg.dggcloud.service.iboss.utils.DataWrap;
import net.dgg.dggcloud.service.jrcrm.entity.cms.UserSetting;
import net.dgg.dggcloud.service.jrcrm.service.cms.MessageService;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

/**
 * @class_name: InProcessService
 * @package: net.dgg.dggcloud.service.iboss.service.sc
 * @describe: TODO 生产订单待分配-service层
 * @creat_user: 孙上峰
 * @creat_date: 2018/06/20
 * @creat_time: 17:33
 **/
@Service
public class WaitAllocationService extends BaseService {
    @Resource
    private WaitAllocationDao waitAllocationDao;
    @Autowired
    private MessageService messageService;

    /**
     * 待分配的生产订单
     *
     * @param map
     * @return
     */
    public List<Map> listWaitAllocationByMap(Map map) {
        return waitAllocationDao.listWaitAllocationByMap(map);
    }

    public Integer countWaitAllocationByMap(Map map) {
        return waitAllocationDao.countWaitAllocationByMap(map);
    }

    /**
     * 分配订单
     *
     * @param id
     */
    public void updateAllotOrder(String id, String flowUserId) {
        User user = SessionManager.getCurrentUser();
        Assert.notNull(user, "当前用户获取失败，请刷新重新登录！");
        ScProOrder scProOrder = this.repository.get(ScProOrder.class, Long.valueOf(id));
        Assert.isTrue(scProOrder.getStatus().equals(ScStatusConstant.WAIT_ALLOCATION), "当前生产订单已不在待分配状态,请刷新列表！");
        Assert.notNull(scProOrder, "没有查询到该生产订单的信息！");
        User flowUser = this.repository.get(User.class, Long.valueOf(flowUserId));
        Assert.notNull(flowUser, "没有查询到选择的流程人员信息！");
        OrganizationEntity org = this.repository.get(OrganizationEntity.class, flowUser.getOrgId());
        scProOrder.setStatus(ScStatusConstant.RECEIVE_WAITING); //待接收
        scProOrder.setFlowUserId(flowUser.getId());
        scProOrder.setFlowUserName(flowUser.getName().concat("(").concat(org.getName()).concat(")")); //流程人员
        scProOrder.setFlowDeptId(org.getId());
        scProOrder.setFlowDeptName(org.getName());
        DataWrap.updateWraps(scProOrder);

        //保存流程操作记录
        ScProFlowOperating scProFlowOperating = new ScProFlowOperating();
        scProFlowOperating.setProProductId(scProOrder.getId());
        scProFlowOperating.setProProductNo(scProOrder.getOrderBusinessNo());
        scProFlowOperating.setFlowUserId(user.getId());
        scProFlowOperating.setFlowUserName(scProOrder.getFlowUserName());
        scProFlowOperating.setStatus(scProOrder.getStatus());
        scProFlowOperating.setOperation("手动分配订单");
        scProFlowOperating.setOperationType(ScOperationConstant.OPERATION_ORDER_WAIT_ALLOCATION_PEOPLE);//分配订单
        DataWrap.saveWrap(scProFlowOperating);
        scProFlowOperating.setId(this.keyWorker.nextId());
        scProOrder.setFlowLatestOperationId(scProFlowOperating.getId()); //流程操作的最新id
        updateUserSetting(scProOrder, "2");
        this.repository.save(scProFlowOperating);
        this.repository.saveOrUpdate(scProOrder);
        try {
            String swCode = "SC_ZDFD_001";
            String flowCode = "SC_ZDFD_002";
            String[] vals = new String[2];
            String[] vals1 = new String[1];
            vals[0] = String.valueOf(scProOrder.getOrderNo());
            vals[1] = String.valueOf(scProOrder.getFlowUserName());
            User swUser = this.repository.get(User.class, scProOrder.getSigningUserId());
            User lcUser = this.repository.get(User.class, scProOrder.getFlowUserId());
            vals1[0] = String.valueOf(scProOrder.getOrderBusinessNo());
            //发送商务推送
            this.messageService.sendMessageReady(swUser, user, vals, swCode);
            //发送后台推送
            this.messageService.sendMessageReady(lcUser, user, vals1, flowCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 自动分配计算流程人员实际接单量
     *
     * @param scProOrder 生产订单
     * @param type       1减 2加
     */
    public void updateUserSetting(ScProOrder scProOrder, String type) {

        if (null == type || "".equals(type)) {
            return;
        }
        //判断当前订单的业务类型(不是资金业务的)
        if (scProOrder.getBtCode().equals(BusCodeConstant.BUS_YT_ZJYW)) {
            return;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, 2018);
        calendar.set(Calendar.MONTH, 6);
        calendar.set(Calendar.DATE, 1);
        calendar.set(Calendar.HOUR, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        //判断这个订单是否是自动接单后接单的
        if (scProOrder.getCreateTime().getTime() < calendar.getTimeInMillis()) {
            return;
        }
        UserSetting userSetting = new UserSetting();
        if (ScStatusConstant.SWITCH_WAITING.equals(scProOrder.getStatus())) {
            userSetting = (UserSetting) repository.getSession().createCriteria(UserSetting.class).add(Restrictions.idEq(scProOrder.getWaitingReceiverId())).uniqueResult();
        } else {
            userSetting = (UserSetting) repository.getSession().createCriteria(UserSetting.class).add(Restrictions.idEq(scProOrder.getFlowUserId())).uniqueResult();
        }
        if (null == userSetting) {
            return;
        }
        //减1
        if (type.equals("1")) {
            updateCutDownOrder(userSetting);
        }
        //加1
        if (type.equals("2")) {
            updatePlusOrder(userSetting);
        }
    }

    /**
     * 减1
     *
     * @param userSetting
     */
    public void updateCutDownOrder(UserSetting userSetting) {
        userSetting.setPolicyRealNum((userSetting.getPolicyRealNum() == null || userSetting.getPolicyRealNum() == 0) ? 0 : userSetting.getPolicyRealNum() - 1);
        this.repository.saveOrUpdate(userSetting);
    }

    /**
     * 加1
     */
    public void updatePlusOrder(UserSetting userSetting) {
        userSetting.setPolicyRealNum((userSetting.getPolicyRealNum() == null || userSetting.getPolicyRealNum() == 0) ? 1 : userSetting.getPolicyRealNum() + 1);
        this.repository.saveOrUpdate(userSetting);
    }

}
